package com.yn.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.yn.common.enums.UserIdentityEnum;
import com.yn.common.exception.TransitException;
import com.yn.common.model.user.User;
import com.yn.common.model.zy.CarDeparturePlanDO;
import com.yn.common.model.zy.CarDepartureService;
import com.yn.common.model.zy.TCarFleetManageDO;
import com.yn.common.model.zy.TCarManageDO;
import com.yn.common.model.zyorder.ZyServiceConfig;
import com.yn.common.page.BasePage;
import com.yn.common.request.driver.DeparturePlanRequest;
import com.yn.common.request.driver.ReturnPlanModifyRequest;
import com.yn.common.request.sc.PageParamRequest;
import com.yn.common.request.zy.ReturnPlanQuery;
import com.yn.common.response.driver.DepartureDetailResponse;
import com.yn.common.response.driver.DeparturePlanResponse;
import com.yn.common.response.driver.ReturnServiceConfigResponse;
import com.yn.common.response.sc.OrderDetailResponse;
import com.yn.common.utils.DateUtil;
import com.yn.service.dao.zy.CarDeparturePlanMapper;
import com.yn.service.service.*;
import com.yn.service.zy.TCarFleetManageService;
import com.yn.service.zy.TCarManageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 司机返程计划表 服务实现类
 * </p>
 *
 * @author xuquanjun
 * @since 2025-07-02
 */
@Service
public class CarDeparturePlanServiceImpl extends ServiceImpl<CarDeparturePlanMapper, CarDeparturePlanDO> implements ICarDeparturePlanService {
    @Resource
    private UserService userService;
    @Resource
    private TCarFleetManageService fleetManageService;
    @Resource
    private ICarDepartureServiceService departureServiceService;
    @Resource
    private ZyServiceConfigService serviceConfigService;

    @Override
    @Transactional
    public Integer DriverPublishOrder(DeparturePlanRequest request) {
        //获取当前登录用户
        User user = userService.getInfoException();
        /*if(Objects.equals(user.getIdentity(), UserIdentityEnum.ORDINARY_USER.getCode()) || Objects.equals(user.getIdentity(), UserIdentityEnum.ESCORT_PERSONNEL.getCode())){
            throw new TransitException("您没有权限发布返车计划");
        }*/

        CarDeparturePlanDO carDeparturePlanDO = new CarDeparturePlanDO();

        BeanUtil.copyProperties(request,carDeparturePlanDO);

        carDeparturePlanDO.setAppUserId(user.getUid());
        //发车时间
        Date date = DateUtil.strToDate(request.getDepartureTime(), DatePattern.NORM_DATETIME_PATTERN);
        if (date != null && date.getTime() < System.currentTimeMillis()) {
            throw new RuntimeException("发车时间不能早于当前时间");
        }
        carDeparturePlanDO.setDepartureTime(date);


            TCarFleetManageDO one = fleetManageService.getById(request.getCarFleetId());
            if(one== null || !Objects.equals(one.getAppUserId(), user.getUid())){
                throw new TransitException("您没有车队信息");
            }
            carDeparturePlanDO.setCarFleetId(one.getId());

        save(carDeparturePlanDO);
        List<Integer> configIds = request.getServiceConfigIds();
        //添加服务项信息
        if(!configIds.isEmpty()){
            ArrayList<CarDepartureService> list = new ArrayList<>();
            for (Integer configId : configIds) {
                CarDepartureService carDepartureService = new CarDepartureService();
                carDepartureService.setDeparturePlanId(carDeparturePlanDO.getId());
                carDepartureService.setServiceConfigId(configId);
                list.add(carDepartureService);
            }
            boolean isSave = departureServiceService.saveBatch(list);
            if(!isSave){
                throw new RuntimeException("添加服务项信息失败");
            }
        }

        return carDeparturePlanDO.getId();
    }

    @Override
    public BasePage<DeparturePlanResponse> orderList(ReturnPlanQuery query, PageParamRequest pageRequest, User user) {
        PageHelper.startPage(pageRequest.getPage(), pageRequest.getLimit());
        LambdaQueryWrapper<CarDeparturePlanDO> lambdaQuery = Wrappers.lambdaQuery();
        if (query.getBeginTime() != null && !query.getBeginTime().isEmpty()) {
            lambdaQuery.between(CarDeparturePlanDO::getDepartureTime, query.getBeginTime(), query.getEndTime());
        }
        if (query.getDesc() != null && query.getDesc() > 0) {
            lambdaQuery.orderByDesc(CarDeparturePlanDO::getDepartureTime);
        } else {
            lambdaQuery.orderByAsc(CarDeparturePlanDO::getDepartureTime);
        }
        if (user != null && user.getIdentity().equals(UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode())) {
            lambdaQuery.eq(CarDeparturePlanDO::getAppUserId, user.getUid());
        }
        //发车时间比当前时间大
        lambdaQuery.gt(CarDeparturePlanDO::getDepartureTime, new Date());
        List<CarDeparturePlanDO> planDOList = this.list(lambdaQuery);
        if (CollUtil.isEmpty(planDOList)) {
            return BasePage.restPage(new ArrayList<>());
        }
        BasePage<CarDeparturePlanDO> restedPage = BasePage.restPage(planDOList);
        ArrayList<DeparturePlanResponse> responseList = new ArrayList<>(planDOList.size());
        boolean isNotUser;
        if( user == null){
            isNotUser = true;
        } else {
            isNotUser = false;
        }
        List<Integer> fleetIds = planDOList.stream().map(CarDeparturePlanDO::getCarFleetId).collect(Collectors.toList());
        List<TCarFleetManageDO> fleetDOList = fleetManageService.listByIds(fleetIds);
        if (CollUtil.isEmpty(fleetDOList)) {
            return BasePage.restPage(new ArrayList<>());
        }
        for (CarDeparturePlanDO planDO : planDOList) {
            DeparturePlanResponse transform = DeparturePlanResponse.transform(planDO);

            fleetDOList.stream().filter(manageDO -> manageDO.getId().equals(planDO.getCarFleetId())).findFirst().ifPresent(manageDO -> {
                transform.setCarFleetName(manageDO.getFleetName());
                //管理端
                if (isNotUser) {
                    transform.setFleetCuratorName(manageDO.getFleetCuratorName());
                    transform.setFleetCuratorPhonenumber(manageDO.getFleetCuratorPhonenumber());
                }
            });
            responseList.add(transform);
        }
        BasePage<DeparturePlanResponse> page = BasePage.restPage(responseList);
        BeanUtils.copyProperties(restedPage, page, "list");
        return page;
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        //获取用户信息
        User user = userService.getInfoException();
        if(!Objects.equals(user.getIdentity(), UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode())){
            throw new TransitException("您没有权限删除该订单");
        }
        baseMapper.deleteById(id);
        CarDepartureService carDepartureService = new CarDepartureService();
        carDepartureService.setDeparturePlanId(id);
        boolean remove = departureServiceService.lambdaUpdate().eq(CarDepartureService::getDeparturePlanId, id).remove();
        if(!remove){
            throw new TransitException("删除失败");
        }
    }

    @Override
    @Transactional
    public void updateReturnPlan(ReturnPlanModifyRequest request, Integer userId) {
        CarDeparturePlanDO carDeparturePlanDO = new CarDeparturePlanDO();

        BeanUtils.copyProperties(request,carDeparturePlanDO);
        carDeparturePlanDO.setAppUserId(userId);
        //发车时间
        carDeparturePlanDO.setDepartureTime(DateUtil.strToDate(request.getDepartureTime(), DatePattern.NORM_DATETIME_PATTERN));
        updateById(carDeparturePlanDO);
        //先删除在更新
        departureServiceService.lambdaUpdate().eq(CarDepartureService::getDeparturePlanId, request.getId()).remove();
        List<Integer> configIds = request.getServiceConfigIds();
        //添加服务项信息
        if(CollectionUtil.isNotEmpty(configIds)){
            ArrayList<CarDepartureService> list = new ArrayList<>();
            for (Integer configId : configIds) {
                CarDepartureService carDepartureService = new CarDepartureService();
                carDepartureService.setDeparturePlanId(carDeparturePlanDO.getId());
                carDepartureService.setServiceConfigId(configId);
                list.add(carDepartureService);
            }
            if (CollUtil.isEmpty(list)){
                throw new TransitException("添加服务项信息失败");
            }
            boolean isSave = departureServiceService.saveBatch(list);
            if(!isSave){
                throw new RuntimeException("添加服务项信息失败");
            }
        }
    }

    @Override
    public DepartureDetailResponse OrderDetail(Integer id,User user) {
        //获取用户信息
        DepartureDetailResponse response = new DepartureDetailResponse();
        LambdaQueryWrapper<CarDeparturePlanDO> lambdaQuery = Wrappers.lambdaQuery();
        if (user != null && Objects.equals(user.getIdentity(), UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode())) {
            //司机只能看见自己的订单详情
            lambdaQuery.eq(CarDeparturePlanDO::getAppUserId, user.getUid());
        }
        lambdaQuery.eq(CarDeparturePlanDO::getId, id);
        CarDeparturePlanDO planDO = baseMapper.selectOne(lambdaQuery);
        if(planDO == null){
            throw new TransitException("订单不存在");
        }
        TCarFleetManageDO fleetInfo = fleetManageService.getById(planDO.getCarFleetId());
        if(fleetInfo == null){
            throw new TransitException("车队信息不存在");
        }
        //封装基础信息(所有端都能看见的信息)
        BeanUtil.copyProperties(planDO, response);
        response.setCarFleetName(fleetInfo.getFleetName());
        //发车时间
        response.setDepartureTime(DateUtil.dateToStr(planDO.getDepartureTime(), DatePattern.NORM_DATETIME_PATTERN));
        //服务项
        List<CarDepartureService> list = departureServiceService.lambdaQuery().eq(CarDepartureService::getDeparturePlanId, planDO.getId()).list();
        if(CollUtil.isEmpty(list)){
            response.setServiceConfigs(new ArrayList<>());
        }else{
            List<ReturnServiceConfigResponse> serviceConfigs = new ArrayList<>();
            List<Integer> configIds = list.stream().map(CarDepartureService::getServiceConfigId).collect(Collectors.toList());
            List<ZyServiceConfig> zyServiceConfigs = serviceConfigService.listByIds(configIds);
            if(CollUtil.isEmpty(zyServiceConfigs)){
                throw new TransitException("服务项配置有问题");
            }
            for (ZyServiceConfig serviceConfig : zyServiceConfigs) {
                ReturnServiceConfigResponse serviceConfigResponse = new ReturnServiceConfigResponse();
                serviceConfigResponse.setId(serviceConfig.getId());
                serviceConfigResponse.setServiceConfigName(serviceConfig.getServiceName());
                serviceConfigs.add(serviceConfigResponse);
            }
            response.setServiceConfigs(serviceConfigs);
        }


        if(user!=null && Objects.equals(user.getIdentity(), UserIdentityEnum.ORDINARY_USER.getCode())){
            //普通用户可以查看所有顺风车订单的基础信息
            return response;
        }
        /*if(Objects.equals(user.getIdentity(), UserIdentityEnum.ESCORT_PERSONNEL.getCode())){
            //医护人员不能看见信息
            return null;
        }*/

        //管理人员和司机可以查看所有顺风车订单的所有信息
        response.setCarFleetAddress(fleetInfo.getFleetAddress());
        response.setFleetCuratorName(fleetInfo.getFleetCuratorName());
        response.setFleetCuratorPhonenumber(fleetInfo.getFleetCuratorPhonenumber());
        return response;
    }
}
